package client.GUI.dashboard;

import java.awt.BorderLayout;
import java.awt.Label;

import client.GUI.GUIConstants;
import client.backend.price.PriceController;
import client.backend.user.UserInformation;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.io.IOException;

public class AccountsPanel extends JPanel {

	private JTable table = null;
	private static AccountsPanel instance = null;

	/**
	 * Default constructor. Generates a account info table
	 */
	private AccountsPanel() {
		super();
		
		JLabel title = new JLabel("Currency Balances");
		
		title.setBounds(0, 345, 512, 30);
    	title.setForeground(GUIConstants.Text_Color);
    	title.setHorizontalAlignment(SwingConstants.CENTER);

		this.add(title);
		table = new JTable(createTable(), GUIConstants.getAccountsColumnNames());
		
		JScrollPane scrollPane = new JScrollPane(table);
	        
	    this.add(scrollPane, BorderLayout.CENTER);
	    
	    this.setBackground(Color.black);
	}
	
	/**
	 * Gets data from an instance
	 */
	public static AccountsPanel getInstance() {
		 if (instance == null) {
				instance = new AccountsPanel();
			}
			return instance;
	}
	
	/**
	 * Creates the table
	 * @return 2D String array holding table elements
	 */
	public String[][] createTable(){
		String [][] currInfo = new String[GUIConstants.Currencies.length][2];
		
		int i = 0;
		for(String curr : PriceController.getInstance().getCurrs()){
			currInfo[i][0] = UserInformation.getInstance().getUser().getAccount(curr).getSymbol();
			currInfo[i][1] = UserInformation.getInstance().getUser().getAccount(curr).getAmount() + "";
			
			i++;
		}
		
		return currInfo;
	}
	
	/**
	 * Refreshes the table for updated info
	 */
	public void refreshTable() {
		if (table != null) {		
			DefaultTableModel model = (DefaultTableModel)table.getModel();
			model.setDataVector(createTable(), GUIConstants.getAccountsColumnNames());

			this.updateUI();
		}
	}
}
